/*
 * @Author: hongbin
 * @Date: 2022-11-03 19:46:29
 * @LastEditors: hongbin
 * @LastEditTime: 2022-11-21 15:01:17
 * @Description:
 */
import { createRef, FC, useCallback, useEffect, useImperativeHandle, useState } from "react";
import styled from "styled-components";
import { useAuth } from "../../context/AuthProvide";
import { SetState } from "../../meta/types";
import { Capitalize, fadeIn, flexCenter } from "../../styled";
import Authentication from "../Authentication";
import UserState from "./UserState";

interface IProps {}

const getLocalInfo = () => {
    const info = JSON.parse(localStorage.getItem("userInfo") || "null");
    return info;
};

export const closePlaneRef = createRef<{ setShow: SetState<boolean> }>();

const HeadPortrait: FC<IProps> = () => {
    const { user } = useAuth();
    const [show, setShow] = useState(false);
    const [option, setOption] = useState<"LOGIN" | "REGISTER">("LOGIN");
    const [showUserState, setShowUserState] = useState(false);

    useImperativeHandle(
        closePlaneRef,
        () => ({
            setShow,
        }),
        [setShow]
    );

    useEffect(() => {
        /**
         * 检测以前是否进入过网站 没进过 点开时注册 否则是登录
         */
        if (!localStorage.getItem("userInfo")) setOption(() => "REGISTER");
    }, []);

    const setDialogState = useCallback(
        (state: boolean) => () => {
            setShow(state);
        },
        []
    );

    const mouseEvent = {
        onMouseEnter: () => user.name && setShowUserState(true),
        onMouseLeave: () => setShowUserState(false),
    };

    return (
        <Container {...mouseEvent}>
            <EyeCatching onClick={() => user.name || setDialogState(true)()}>
                {user.name ? user.name.slice(0, 2) : "登陆"}
            </EyeCatching>
            {show ? <Mask onClick={setDialogState(false)} /> : null}
            <Authentication show={show} option={option} setOption={setOption} />
            <UserState {...mouseEvent} userInfo={user} show={showUserState && !!user.name} />
        </Container>
    );
};

export default HeadPortrait;

const Mask = styled.div`
    position: fixed;
    width: 100vw;
    height: 100vh;
    top: 0;
    left: 0;
    transition: all 0.3s linear;
    animation: ${fadeIn} 0.3s;
    background-color: #00000044;
`;

const EyeCatching = styled.span`
    font-weight: bold;
    font-size: 1.5vmax;
    color: #ffffff;
    transition: opacity 0.3s linear;
    ${Capitalize}
`;

const Container = styled.div`
    position: absolute;
    top: 1vmax;
    right: 1vmax;
    width: 4vmax;
    height: 4vmax;
    border-radius: 4vmax;
    border: 2px solid #045510;
    cursor: pointer;
    z-index: 11;
    background-color: #18610c;
    ${flexCenter};
    box-shadow: ${(props) => props.theme.boxShadow};
`;
